import os
from typing import Dict, Any
from dotenv import load_dotenv

# 加载环境变量
load_dotenv()

class Config:
    """FastAPI应用配置类"""
    
    # 基础配置
    APP_NAME = 'Quantitative Advanced Backend'
    APP_VERSION = '1.0.0'
    DEBUG = os.environ.get('FASTAPI_ENV') == 'development'
    
    # 服务器配置
    HOST = os.environ.get('HOST', '0.0.0.0')
    PORT = int(os.environ.get('PORT', 5001))
    
    # 日志配置
    LOG_LEVEL = os.environ.get('LOG_LEVEL', 'INFO')
    LOG_FILE = os.environ.get('LOG_FILE', None)
    
    # LongPort API配置
    LONGPORT_APP_KEY = os.environ.get('LONGPORT_APP_KEY')
    LONGPORT_APP_SECRET = os.environ.get('LONGPORT_APP_SECRET')
    LONGPORT_ACCESS_TOKEN = os.environ.get('LONGPORT_ACCESS_TOKEN')
    
    # 数据获取配置
    DATA_TIMEOUT = int(os.environ.get('DATA_TIMEOUT', 30))
    DATA_CACHE_TIMEOUT = int(os.environ.get('DATA_CACHE_TIMEOUT', 0))  # 禁用缓存
    
    # 缓存配置 - 禁用缓存
    CACHE_ENABLED = False  # 禁用缓存
    CACHE_DIR = None  # 不设置缓存目录
    CACHE_DEFAULT_TTL = 0  # 缓存TTL设为0
    
    # 恐贪指标配置
    FEAR_GREED_INDICATORS = {
        'momentum': 0.25,      # 动量指标权重
        'volatility': 0.25,    # 波动率指标权重
        'market_volume': 0.25, # 市场成交量权重
        'put_call_ratio': 0.25 # 看跌看涨比率权重
    }
    
    # 技术指标配置
    TECHNICAL_INDICATORS = {
        'RSI': {'window': 14, 'overbought': 70, 'oversold': 30},
        'MACD': {'fast': 12, 'slow': 26, 'signal': 9},
        'BB': {'window': 20, 'std': 2},
        'STOCH': {'window': 14, 'smooth': 3},
        'ATR': {'window': 14},
        'ADX': {'window': 14}
    }
    
    # 默认股票配置
    DEFAULT_SYMBOLS = ['AAPL', 'GOOGL', 'MSFT', 'AMZN', 'TSLA']
    DEFAULT_MARKET_INDEX = 'SPY'
    
    # API配置
    API_RATE_LIMIT = int(os.environ.get('API_RATE_LIMIT', 100))  # 每分钟请求数
    API_TIMEOUT = int(os.environ.get('API_TIMEOUT', 30))
    
    # CORS配置
    CORS_ORIGINS = os.environ.get('CORS_ORIGINS', '*').split(',')
    CORS_ALLOW_CREDENTIALS = True
    CORS_ALLOW_METHODS = ["*"]
    CORS_ALLOW_HEADERS = ["*"]
    
    # 恐贪指标范围配置
    FEAR_GREED_RANGE = {
        'min': -100,
        'max': 100,
        'neutral': 0
    }
    
    # 历史数据配置
    HISTORICAL_DATA_PERIOD = '1y'  # 默认获取一年数据
    MIGRATION_PERIOD = '6m'         # 半年迁移期
    
    @classmethod
    def get_logging_config(cls) -> Dict[str, Any]:
        """获取日志配置"""
        return {
            'level': cls.LOG_LEVEL,
            'file': cls.LOG_FILE,
            'format': '%(asctime)s - %(name)s - %(levelname)s - %(message)s',
            'date_format': '%Y-%m-%d %H:%M:%S'
        }
    
    @classmethod
    def get_longport_config(cls) -> Dict[str, Any]:
        """获取LongPort API配置"""
        return {
            'app_key': cls.LONGPORT_APP_KEY,
            'app_secret': cls.LONGPORT_APP_SECRET,
            'access_token': cls.LONGPORT_ACCESS_TOKEN,
            'timeout': cls.DATA_TIMEOUT
        }
    
    @classmethod
    def validate_longport_config(cls) -> bool:
        """验证LongPort配置是否完整"""
        return all([
            cls.LONGPORT_APP_KEY,
            cls.LONGPORT_APP_SECRET,
            cls.LONGPORT_ACCESS_TOKEN
        ])
    
    @classmethod
    def get_fear_greed_config(cls) -> Dict[str, Any]:
        """获取恐贪指标配置"""
        return {
            'indicators': cls.FEAR_GREED_INDICATORS,
            'range': cls.FEAR_GREED_RANGE,
            'historical_period': cls.HISTORICAL_DATA_PERIOD,
            'migration_period': cls.MIGRATION_PERIOD
        }

class DevelopmentConfig(Config):
    """开发环境配置"""
    DEBUG = True
    LOG_LEVEL = 'DEBUG'
    FASTAPI_ENV = 'development'

class ProductionConfig(Config):
    """生产环境配置"""
    DEBUG = False
    LOG_LEVEL = 'WARNING'
    FASTAPI_ENV = 'production'

class TestingConfig(Config):
    """测试环境配置"""
    TESTING = True
    DEBUG = True
    FASTAPI_ENV = 'testing'

# 配置映射
config_map = {
    'development': DevelopmentConfig,
    'production': ProductionConfig,
    'testing': TestingConfig,
    'default': DevelopmentConfig
}

def get_config(env: str = None) -> Config:
    """
    获取配置
    
    Args:
        env: 环境名称
        
    Returns:
        配置对象
    """
    if env is None:
        env = os.environ.get('FASTAPI_ENV', 'default')
    
    return config_map.get(env, config_map['default']) 